package com.github.od.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.github.od.exception.auth.ClientForbiddenException;
import com.github.od.rpc.ClientAuthRpc;
import com.github.od.util.ClientTokenUtil;
import com.github.od.util.jwt.IJWTInfo;
import com.github.od.vo.BaseResponse;
import com.github.od.vo.ObjectRestResponse;

/**
 * 客户端拦截器
 * 
 * @author xieweikun
 * @version 2017年11月19日 下午8:17:29
 */
@Configuration
public class ClientInterceptor extends HandlerInterceptorAdapter {

	@Value("${client.token-header}")
	private String tokenHeader;
	@Value("${client.id}")
	private String clientId;
	@Value("${client.secret}")
	private String secret;
	@Autowired
	private ClientTokenUtil clientTokenUtil;
	@Autowired
	private ClientAuthRpc clientAuthRpc;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/*
		 * 校验该项目是否在客户端列表中
		 */
		// 获取请求头
		String token = request.getHeader(tokenHeader);
		// 获取jwt消息
		IJWTInfo info = clientTokenUtil.getInfoFromToken(token);

		/*
		 * 校验该项目是否在可以访问目标项目的列表中
		 */
		// clientName(code)
		String uniqueName = info.getUniqueName();
		// 允许访问的客户端列表
		BaseResponse resp = clientAuthRpc.getAllowedClient(clientId, secret);
		if (resp.getStatus() == 200) {
			ObjectRestResponse<List<String>> allowedClient = (ObjectRestResponse<List<String>>) resp;
			for (String client : allowedClient.getData()) {
				if (client.equals(uniqueName)) {
					return super.preHandle(request, response, handler);
				}
			}
		}
		throw new ClientForbiddenException("Client id Forbidden!");
	}

}
